// packageA/pages/trajectoryRealTime/trajectoryRealTime.js
const app = getApp();
const util = require('../../../utils/util');
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //设置可停留时长
    showStop:false,
    //日期选择框
    showDate:false,
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    //显示的日期
    currentDateStr:util.timeFormatDay(new Date()),
    //明天日期
    tomorrow:util.timeFormatDay (new Date(new Date().getTime()+ 24*60*60*1000)),
    //轨迹
    polyline: [],
    //传参
    paramObj:{},
    //传参来的物联网数据
    iotData:{},
    //运行数据
    runArr:[],
    //地图中心点
    centerLog:'',
    centerLat:'',
    //统计到几天前
    dayNum:60,
    //地图上标记（用于所有轨迹数据在一个点上）
    markers:[],
    //显示切换
    showType: false,
    //端口
    port: null,
    //用户权限
    authority: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      authority: app.globalData.authority
    })

    //设置统计几天数据
    this.getBeforeDate();

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);

      console.log('轨迹传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      let iotData=paramObj.iotData; 

      //定位点
      if(iotData.lng && iotData.lat){
        this.setData({
          iotData: iotData,
          centerLog:iotData.lng,
          centerLat:iotData.lat,
        })
      }else{
        this.setData({
          centerLog:'116.411168',
          centerLat:'39.898331'
        })
      }

      //获取轨迹数据
      this.getTrajectoryData();

    }else{
      Toast.fail('暂无轨迹数据');
      this.setData({
        centerLog:'116.411168',
        centerLat:'39.898331'
      })
    }
  },

  //获取轨迹数据
  getTrajectoryData(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    //清空数据
    this.setData({
      runArr: [],
      polyline: []
    })

    let param={
      imei: this.data.paramObj.imei,
      startTime: this.data.currentDateStr
    }

    CommonService.findRunRecordToPgsql(param).then(res=>{
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log("result");
        console.log(result);
        //时间格式
        result.forEach(item => {
          // item.self_start = item.startTime.slice(11);
          // item.self_end = item.endTime.slice(11);
          item.self_start = item.startTime;
          item.self_end = item.endTime;
          item.self_long = util.secondToFormat(item.intervals/1000);
        });

        console.log('实时轨迹');
        console.log(result);

        this.setData({
          runArr: result
        })

        //显示当天所有数据的轨迹
        this.showAllTrajectory();

      }else{
        Toast.fail('暂无轨迹数据');
        //把定位点显示到地图上
        this.showMarker();
      }

    }).catch((error) => {
      Toast.fail('暂无轨迹数据');
    })
  },

  //判断轨迹数组中的值是否在一个点上
  isOnePoint(arr){
    let lng=arr[0].longitude;
    let lat=arr[0].latitude;

    let lngFlag=arr.every(item=>{
      return item.longitude==lng
    });

    let latFlag=arr.every(item=>{
      return item.latitude==lat
    });

    if(lngFlag && latFlag){
      return true;
    }else{
      return false;
    }
  },

  //显示当天所有数据的轨迹
  showAllTrajectory(){
    let runArr=this.data.runArr;
    let pointsGps=[];
    let gpsObj=null;
    let polyline=[];

    //点集合
    if(runArr.length){
      pointsGps=this.getPoints(runArr); 
      gpsObj={
        points: pointsGps,
        color: "#FF0000DD",
        width: 4,
        arrowLine: true
      }
    }

    //轨迹起点和终点显示定位点
    let markers=[];
    let start1=null,end1=null;

    if(pointsGps.length){
      let len=pointsGps.length-1;

      start1={
        id: 0,
        latitude: pointsGps[0].latitude,
        longitude: pointsGps[0].longitude,
        width: 15,
        height: 15,
        callout:{
          content: '起点',
          display: 'ALWAYS',
          color: '#fff',
          bgColor: '#009999',
          padding: 5
        }
      }

      end1={
        id: 1,
        latitude: pointsGps[len].latitude,
        longitude: pointsGps[len].longitude,
        width: 15,
        height: 15,
        callout:{
          content: '终点',
          display: 'ALWAYS',
          color: '#fff',
          bgColor: '#FF6600',
          padding: 5
        }
      }
    }

    //显示折线和定位点
    polyline.push(gpsObj);
    markers.push(start1,end1);

    this.setData({
      markers: markers,
      //画折线
      polyline: polyline,
      centerLog: pointsGps[0].longitude,
      centerLat: pointsGps[0].latitude
    })
  },

  //得到点集合
  getPoints(runArr){
    let pointsArr=[];

    for(let i=0;i<runArr.length;i++){
      let locationArr=runArr[i].trajectory;
      locationArr.forEach(item => {
        if(item.lng && item.lat){
          let obj={
            longitude: item.lng,
            latitude: item.lat,
          }
          pointsArr.push(obj);
        }
      });
    }

    return pointsArr;
  },

  //点击时段显示轨迹
  onShowTrajectory(e){
    let runArr=this.data.runArr;
    let detail=e.currentTarget.dataset.detail;
    let idx=e.currentTarget.dataset.index;
    let locationArr=detail.trajectory;
    let pointsArr=[];

    //获取坐标
    for(let i=0;i<locationArr.length;i++){
      let obj={
        longitude:locationArr[i].lng,
        latitude:locationArr[i].lat,
      }
      pointsArr.push(obj);
    }

    if(pointsArr.length<=1){
      Toast({
        type: 'fail',
        message: '暂无轨迹数据',
        duration: 1000,
      });
    }

    //当前样式
    for(let i=0;i<runArr.length;i++){
      runArr[i].current=false;
      if(i==idx){
        runArr[i].current=true;
      }
    }

    //轨迹全部相同时显示定位点
    if(this.isOnePoint(pointsArr)){
      let markers=[];
      let marker={
        id:0,
        latitude: pointsArr[0].latitude,
        longitude: pointsArr[0].longitude,
        width:10,
        height:10
      }
      markers.push(marker);
      this.setData({
        markers: markers
      })
    }else{
      this.setData({
        markers: []
      })
    }

    //线颜色
    let color="#FF0000DD"; 

    this.setData({
      //画折线
      polyline: [{
        points: pointsArr,
        color: color,
        width: 4,
        arrowLine: true
      }],
      runArr:runArr,
      centerLog:pointsArr[0].longitude,
      centerLat:pointsArr[0].latitude
    })
  },

  //设置可选的最小日期
  getBeforeDate(){
    let rusult=util.countPrevDay(new Date(),this.data.dayNum);
    this.setData({
			minDate: rusult
		})
  },

  //显示日期选择框
  onShowDate(){
    this.setData({
			showDate: true
		})
  },

  //关闭日期选择框
  onCloseDate(){
    this.setData({
			showDate: false
		})
  },

  //确定日期时
  onConfirmDate(event){
    let currentDate=event.detail;
    this.setData({
      currentDate: currentDate,
      currentDateStr: util.timeFormatDay(currentDate),
      tomorrow: util.timeFormatDay(new Date(currentDate+ 24*60*60*1000)),
    })

    //关闭日期选择框
    this.onCloseDate();

    //请求轨迹数据
    this.getTrajectoryData();
  },

  //点击查看所有轨迹
  onLookAll(){
    this.showAllTrajectory();

    //清除当前样式
    let runArr=this.data.runArr;
    for(let i=0;i<runArr.length;i++){
      runArr[i].current=false;
    }
    this.setData({
      runArr: runArr
		})
  },

  //如果无轨迹数据，把定位点显示到地图上
  showMarker(){
    let markers=[];
    let marker={
      id:0,
      latitude: this.data.centerLat,
      longitude: this.data.centerLog
    }
    markers.push(marker);
    this.setData({
      markers: markers
    })
  },

  //切换轨迹类型
  onChangeType({detail}) {
    let arr=this.data[detail];

    this.setData({
      valueType: detail,
      runArr: arr
    })

    //显示当天所有数据的轨迹
    this.showAllTrajectory();
  },

  //判断端口号
  commonPort(obj) {
    let portNum = obj.port;
    let localAddress = obj.localAddress;
    let port = '';

    if (portNum == 8880 && localAddress == '47.99.141.227') {
      port = 88800;
    } else {
      port = portNum;
    }

    this.setData({
      port: port
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})